package com.ican.study2.common.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ican.study2.common.common.BusinessException;

public class ImageFetchUtil {
    
    private final static Logger logger = LoggerFactory.getLogger(ImageFetchUtil.class);

    public static BufferedImage loadImageLocal(String imgLocal)  throws BusinessException{
        try {
            return ImageIO.read(new File(imgLocal));
        } catch (Exception e) {
            throw new BusinessException("读取本地图片出错（" + imgLocal + "）！", e);
        }
    }

    public static BufferedImage loadImageUrl(String imgUrl) throws BusinessException {
        try {
            URL url = new URL(imgUrl);
            return ImageIO.read(url);
        } catch (Exception e) {
            throw new BusinessException("读取网络图片出错（" + imgUrl + "）！", e);
        }
    }

    public static void loadAndWriteImage(String imgUrl, String path) throws BusinessException {
        int index = imgUrl.lastIndexOf("/") + 1;
        String fileName = imgUrl.substring(index);
        index = fileName.lastIndexOf(".") + 1;
        String fileFormat = fileName.substring(index);
        try {
            ImageIO.write(ImageIO.read(new URL(imgUrl)), fileFormat, new File(path + fileName));
        } catch (Exception e) {
            throw new BusinessException("保存图片出错（" + path + fileName + "）！", e);
        }
    }
    
    public static String loadAndWriteImageNoException(String imgUrl, String path, String fileName){
        if(imgUrl == null || path == null || imgUrl.trim().length() < 1 || path.trim().length() < 1){
            return null;
        }
        try {
            String fileFormat = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
            if(fileName == null){
                fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
            }else{
                fileName = fileName + "." + fileFormat;
            }
            FileUtils.folderIsExists(path);
            ImageIO.write(ImageIO.read(new URL(imgUrl)), fileFormat, new File(path + fileName));
        } catch (Exception e) {
            logger.error("保存图片出错（imgUrl>>" + imgUrl + ">>path>>" + path + "）！", e);
        }
        return fileName;
    }
    
//    public static void main(String[] args){
//        String t = "asdfa.jsp";
//        System.out.println(t.substring(0, t.indexOf(".")));
//    }
}
